<template>
  <canvas ref="canvas" class="absolute top-0 w-full h-[100vh] pointer-events-none" />
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue'

const canvas = ref<HTMLCanvasElement | null>(null)

onMounted(() => {
  if (!canvas.value) return

  const ctx = canvas.value.getContext('2d')!
  canvas.value.width = window.innerWidth
  canvas.value.height = window.innerHeight

  // 粒子系统实现
  class Particle {
    x: number; y: number; size: number;
    speedX: number; speedY: number;

    constructor() {
      this.x = Math.random() * canvas.value!.width
      this.y = Math.random() * canvas.value!.height
      this.size = Math.random() * 2 + 1
      this.speedX = Math.random() * 1 - 0.5
      this.speedY = Math.random() * 1 - 0.5
    }

    update() {
      this.x += this.speedX
      this.y += this.speedY
      if (this.x < 0 || this.x > canvas.value!.width) this.speedX *= -1
      if (this.y < 0 || this.y > canvas.value!.height) this.speedY *= -1
    }

    draw() {
      ctx.fillStyle = 'rgba(99, 102, 241, 0.5)'
      ctx.beginPath()
      ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2)
      ctx.fill()
    }
  }

  const particles = Array(150).fill(null).map(() => new Particle())

  function animate() {
    ctx.clearRect(0, 0, canvas.value!.width, canvas.value!.height)
    particles.forEach(p => {
      p.update()
      p.draw()
      // 连线逻辑
      particles.forEach(p2 => {
        const dx = p.x - p2.x
        const dy = p.y - p2.y
        const dist = Math.sqrt(dx * dx + dy * dy)
        if (dist < 100) {
          ctx.beginPath()
          ctx.strokeStyle = `rgba(99, 102, 241, ${1 - dist / 100})`
          ctx.lineWidth = 0.5
          ctx.moveTo(p.x, p.y)
          ctx.lineTo(p2.x, p2.y)
          ctx.stroke()
        }
      })
    })
    requestAnimationFrame(animate)
  }
  animate()
})
</script>